from models.models import Sentence, UserSentenceAssignment, Recording, User, db
from sqlalchemy import and_

class SentenceController:
    @staticmethod
    def get_all_sentences():
        sentences = Sentence.query.all()
        return {
            'code': 200,
            'message': '获取成功',
            'data': [sentence.to_dict() for sentence in sentences]
        }
    
    @staticmethod
    def search_sentences(keyword):
        if not keyword:
            return SentenceController.get_all_sentences()
        
        sentences = Sentence.query.filter(Sentence.content.like(f'%{keyword}%')).all()
        return {
            'code': 200,
            'message': '获取成功',
            'data': [sentence.to_dict() for sentence in sentences]
        }

    # ==================== 用户分配句子相关功能 ====================

    @staticmethod
    def get_user_assigned_sentences(user_id):
        """获取用户分配的句子列表（按顺序）"""
        try:
            # 查询用户的分配情况
            assignments = db.session.query(
                UserSentenceAssignment,
                Sentence.content
            ).join(
                Sentence, UserSentenceAssignment.sentence_id == Sentence.id
            ).filter(
                UserSentenceAssignment.user_id == user_id
            ).order_by(
                UserSentenceAssignment.sequence_order
            ).all()

            if not assignments:
                return {
                    'code': 200,
                    'message': '暂无分配的句子',
                    'data': {
                        'sentences': [],
                        'total': 0,
                        'completed': 0,
                        'current_index': 0,
                        'has_assignments': False
                    }
                }

            # 构建句子数据
            sentences_data = []
            completed_count = 0
            current_index = 0

            for i, (assignment, content) in enumerate(assignments):
                # 检查是否已录制
                recording = Recording.query.filter_by(
                    user_id=user_id,
                    sentence_id=assignment.sentence_id
                ).first()

                is_completed = recording is not None
                if is_completed:
                    completed_count += 1
                elif current_index == 0:  # 第一个未完成的句子
                    current_index = i

                sentences_data.append({
                    'id': assignment.sentence_id,
                    'content': content,
                    'sequence_order': assignment.sequence_order,
                    'is_completed': is_completed,
                    'assignment_id': assignment.id,
                    'assigned_at': assignment.assigned_at.isoformat() if assignment.assigned_at else None
                })

            # 如果所有句子都完成了，current_index应该指向最后一个
            if completed_count == len(sentences_data):
                current_index = len(sentences_data) - 1

            return {
                'code': 200,
                'message': '获取成功',
                'data': {
                    'sentences': sentences_data,
                    'total': len(sentences_data),
                    'completed': completed_count,
                    'current_index': current_index,
                    'has_assignments': True,
                    'completion_rate': round(completed_count / len(sentences_data) * 100, 1)
                }
            }

        except Exception as e:
            return {'code': 500, 'message': f'获取失败: {str(e)}', 'data': None}

    @staticmethod
    def get_next_unrecorded_sentence(user_id):
        """获取下一个待录制的句子"""
        try:
            # 查询下一个未录制的分配句子
            next_assignment = db.session.query(
                UserSentenceAssignment,
                Sentence.content
            ).join(
                Sentence, UserSentenceAssignment.sentence_id == Sentence.id
            ).outerjoin(
                Recording, and_(
                    Recording.user_id == user_id,
                    Recording.sentence_id == UserSentenceAssignment.sentence_id
                )
            ).filter(
                UserSentenceAssignment.user_id == user_id,
                Recording.id.is_(None)  # 没有录音记录
            ).order_by(
                UserSentenceAssignment.sequence_order
            ).first()

            if not next_assignment:
                # 检查是否有分配但都已完成
                total_assignments = UserSentenceAssignment.query.filter_by(user_id=user_id).count()
                if total_assignments > 0:
                    return {
                        'code': 200,
                        'message': '所有分配的句子都已录制完成',
                        'data': {
                            'sentence': None,
                            'all_completed': True,
                            'has_assignments': True
                        }
                    }
                else:
                    return {
                        'code': 200,
                        'message': '暂无分配的句子',
                        'data': {
                            'sentence': None,
                            'all_completed': False,
                            'has_assignments': False
                        }
                    }

            assignment, content = next_assignment

            return {
                'code': 200,
                'message': '获取成功',
                'data': {
                    'sentence': {
                        'id': assignment.sentence_id,
                        'content': content,
                        'sequence_order': assignment.sequence_order,
                        'assignment_id': assignment.id
                    },
                    'all_completed': False,
                    'has_assignments': True
                }
            }

        except Exception as e:
            return {'code': 500, 'message': f'获取失败: {str(e)}', 'data': None}

    @staticmethod
    def get_user_sentence_progress(user_id):
        """获取用户句子录制进度"""
        try:
            # 统计分配和完成情况
            total_assigned = UserSentenceAssignment.query.filter_by(user_id=user_id).count()

            if total_assigned == 0:
                return {
                    'code': 200,
                    'message': '暂无分配的句子',
                    'data': {
                        'total_assigned': 0,
                        'completed': 0,
                        'pending': 0,
                        'completion_rate': 0,
                        'has_assignments': False
                    }
                }

            # 统计已完成的数量
            completed_count = db.session.query(UserSentenceAssignment).join(
                Recording, and_(
                    Recording.user_id == UserSentenceAssignment.user_id,
                    Recording.sentence_id == UserSentenceAssignment.sentence_id
                )
            ).filter(
                UserSentenceAssignment.user_id == user_id
            ).count()

            pending = total_assigned - completed_count
            completion_rate = round(completed_count / total_assigned * 100, 1)

            return {
                'code': 200,
                'message': '获取成功',
                'data': {
                    'total_assigned': total_assigned,
                    'completed': completed_count,
                    'pending': pending,
                    'completion_rate': completion_rate,
                    'has_assignments': True
                }
            }

        except Exception as e:
            return {'code': 500, 'message': f'获取进度失败: {str(e)}', 'data': None}